package com.ml4ai.core.stack.elasticsearch;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * Created by leecheng on 2018/11/25.
 */
public class BoolBuilderCreator {

    public static BoolQueryBuilder createBoolQueryBuilder(Map<String, Object> condition) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        Set<String> keys = condition.keySet();
        for (String key : keys) {
            String[] keySplit = key.split(" ");
            String field = keySplit[0];
            String queryMethod = "=";
            if (keySplit.length > 1) {
                queryMethod = keySplit[1];
            }
            switch (queryMethod) {
                case "term":
                case "=":
                    boolQueryBuilder.must(QueryBuilders.termQuery(field, condition.get(key)));
                    break;
                case "in":
                    if (condition.get(key) instanceof Collection) {
                        boolQueryBuilder.must(QueryBuilders.termsQuery(field, (Collection) condition.get(key)));
                    } else if (condition.get(key) instanceof Object[]) {
                        boolQueryBuilder.must(QueryBuilders.termsQuery(field, (Object[]) condition.get(key)));
                    }
                    break;
                case "match":
                case "matchOR":
                    boolQueryBuilder.must(QueryBuilders.matchQuery(field, condition.get(key)).operator(Operator.OR));
                    break;
                case "matchAND":
                    boolQueryBuilder.must(QueryBuilders.matchQuery(field, condition.get(key)).operator(Operator.AND));
                    break;
                default:
                    throw new IllegalStateException(String.format("不支持的类型：[%d]，仅支持[=,term,match,matchOR,matchAND]", queryMethod));
            }
        }
        return boolQueryBuilder;
    }

}
